//
//  UIImage.swift
//  funcode
//
//  Created by Wan Jiading on 2017/9/18.
//  Copyright © 2017年 WanJiading. All rights reserved.
//

import UIKit

enum GuadientType: Int {
    case leftToRight            // 从左到右
    case rightToLeft            // 从右到左
    case topToBottom            // 从上到下
    case bottomToTop            // 从下到上
    case leftTopToRightBottom   // 从左上到右下
    case rightBottomToLeftTop   // 从右下到左上
    case leftBottomToRightTop   // 从左下到右上
    case rightTopToLeftBottom   // 从右上到左下
}

extension UIImage {

    class func gradientColorImage(_ colors: [UIColor], _ type: GuadientType, _ imgSize: CGSize) -> UIImage {
        let cgColors = NSMutableArray()
        for c in colors {
            cgColors.add(c.cgColor)
        }
        
        UIGraphicsBeginImageContextWithOptions(imgSize, true, 1)
        let context = UIGraphicsGetCurrentContext()
        context!.saveGState()
        let colorSpace = CGColorSpaceCreateDeviceRGB()
        let gradient = CGGradient(colorsSpace: colorSpace, colors: cgColors, locations: nil)
        
        let width = imgSize.width
        let height = imgSize.height
        
        var start: CGPoint
        var end: CGPoint
        
        switch type {
        case .leftToRight:
            start = CGPoint(x: 0, y: 0)
            end = CGPoint(x: width, y: 0)
        case .rightToLeft:
            start = CGPoint(x: width, y: 0)
            end = CGPoint(x: 0, y: 0)
        case .topToBottom:
            start = CGPoint(x: 0, y: 0)
            end = CGPoint(x: 0, y: height)
        case .bottomToTop:
            start = CGPoint(x: 0, y: height)
            end = CGPoint(x: 0, y: 0)
        case .leftTopToRightBottom:
            start = CGPoint(x: 0, y: 0)
            end = CGPoint(x: width, y: height)
        case .rightBottomToLeftTop:
            start = CGPoint(x: width, y: height)
            end = CGPoint(x: 0, y: 0)
        case .leftBottomToRightTop:
            start = CGPoint(x: 0, y: height)
            end = CGPoint(x: width, y: 0)
        case .rightTopToLeftBottom:
            start = CGPoint(x: width, y: 0)
            end = CGPoint(x: 0, y: height)
        }
        
        context!.drawLinearGradient(gradient!, start: start, end: end, options: CGGradientDrawingOptions.drawsBeforeStartLocation)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        
        UIGraphicsEndImageContext()
        
        return image!
    }
    
}
